<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>2.事件代理</title>
  <style type="text/css">
    div {
      border: 1px solid #ccc;
      margin: 10px 0;
      padding: 1 10px;
    }
  </style>
</head>

<body>

  事件代理---运用了事件冒泡的原理

  1.代码简洁
  2.减少浏览器内存占用
  3.但是不要滥用


  <div id="div3">
    <a href="#">a1</a>
    <a href="#">a2</a>
    <a href="#">a3</a>
    <a href="#">a4</a>
    <a href="#">a5</a>
    <button>加载更多...</button>
  </div>

  <script>
    const div3 = document.getElementById('div3')
    // 1.通用事件绑定函数
    // function bindEvent(elem, type, fn) {
    //   elem.addEventListener(type, fn)
    // }

    // bindEvent(div3, 'click', event => {
    //   event.preventDefault()
    //   const target = event.target
    //   if (target.nodeName === 'A') {
    //     console.log(target.innerHTML);
    //   }
    // })

    // 2.复杂通用事件绑定函数
    function bindEvent(elem, type, selector, fn) {
      if (fn == null) {
        fn = selector
        selector = null
      }
      elem.addEventListener(type, event => {
        const target = event.target

        if (selector) {
          // 事件代理
          // matches
          if (target.matches(selector)) {
            fn.call(target, event)
          }
        } else {
          // 普通
          fn.call(target, event)
        }
      })
    }

    bindEvent(div3, 'click', 'a', function (event) {
      event.preventDefault()

      console.log(this.innerHTML);
    })

  </script>

</body>

</html>